<template>
	<view class="container">
		<navbar :title="navTitle"></navbar>

		<view class="content">
			<view class="form-box">
				<view class="city">
					<!-- <view class="left" @click="$refs.selectCity.open()"> -->
					<view class="left" @click="openLocation">
						<image :src="$img_path('/pagesMine/68.png')" mode="widthFix"></image>
						<text v-if="!formdata.formatted_address" class="pla-class">点击选择地区</text>
						<text v-else class="value">{{ formdata.formatted_address }}</text>
					</view>
					<view class="dw" @click="openLocation">
						<image :src="$img_path('/pagesMine/67.png')" mode="widthFix"></image>
						<text>定位</text>
					</view>
				</view>

				<view class="city address">
					<view class="left">
						<image :src="$img_path('/pagesMine/69.png')" mode="widthFix"></image>
						<input v-model="formdata.address" type="text" placeholder-class="pla-class"
							placeholder="请输入详细地址" />
					</view>
				</view>

				<view class="city name-sex">
					<view class="left">
						<image :src="$img_path('/pagesMine/70.png')" mode="widthFix"></image>
						<input v-model="formdata.name" type="text" placeholder-class="pla-class" placeholder="请输入姓名" />
					</view>
				</view>

				<view class="city address">
					<view class="left">
						<image style="width: 27rpx;height: 42rpx;" :src="$img_path('/pagesMine/71.png')"
							mode="widthFix"></image>
						<input v-model="formdata.mobile" style="padding-left: 22rpx;" type="number"
							placeholder-class="pla-class" placeholder="请输入手机号码" />
					</view>
				</view>

				<view class="moren">
					<text>设置默认地址</text>
					<switch :checked="isDefault" @change="switchChange" />
				</view>
			</view>
		</view>

		<view class="b-btn">
			<view class="b-box" v-if="navTitle=='新增地址'">
				<button @click="save">保存</button>
			</view>
			<view class="b-box edit" v-if="navTitle=='编辑地址'">
				<button>删除</button>
				<button @click="save">保存</button>
			</view>
		</view>

		<popupBox ref="selectCity" type="bottom" :isSlot="true">
			<view class="select-city-box">
				<view class="title">
					<text>选择省市区</text>
					<image :src="$img_path('/mall/15.png')" @click="closeSelectCity" mode="widthFix"></image>
				</view>

				<view class="s-value" v-if="province">
					<view class="province" :class="">
						<!-- <text class="no-select" v-if="!province">选择省份</text> -->
						<text class="value select" v-if="province">{{province.text}}</text>
						<text class="edit" v-if="province" @click="check(0)">修改</text>
					</view>
					<view class="city" v-if="province">
						<text class="value prev-select" v-if="!city">请选择城市</text>
						<text class="value select" v-else>{{city.text}}</text>
						<text class="edit" v-if="city" @click="check(1)">修改</text>
					</view>
					<view class="arae" v-if="city">
						<text class="value prev-select" v-if="!arae">请选择区/县</text>
						<text class="value select" v-else>{{arae.text}}</text>
						<text class="edit" v-if="arae" @click="check(2)">修改</text>
					</view>

					<view class="detail" v-if="arae">
						<text class="value prev-select" v-if="!detail">请选择街道/镇</text>
						<text class="value select" v-else>{{detail.text}}</text>
						<text class="edit" v-if="detail" @click="check(3)">修改</text>
					</view>
				</view>

				<view class="select-index">
					<text v-if="select_city_index==0">选择省份</text>
					<text v-else-if="select_city_index==1">选择城市</text>
					<text v-else-if="select_city_index==2">选择区/县</text>
					<text v-else>选择街道/镇</text>
				</view>

				<view class="s-list">
					<view class="s-item" v-for="(item, index) in cities" :key="index">
						<text>{{ item.first }}</text>
						<view v-for="(subItem, subIndex) in item.children" :key="subIndex" class="name"
							@click="selectChange(subItem.name)">
							{{ subItem.name }}
						</view>
					</view>
				</view>
			</view>
		</popupBox>
	</view>
</template>

<script>
	import popupBox from '@/components/popup/popup.vue'
	import autoParseAddress from '@/components/auto-parse-address/auto-parse-address.vue';
	import {
		getLocation,
		getCities,
		getSysArea,
		addUserAddress
	} from "@/utils/api/serviceApi.js"
	export default {
		components: {
			autoParseAddress,
			popupBox
		},
		data() {
			return {
				navTitle: '',

				select_city_index: 0,
				province: null,
				city: null,
				arae: null,
				detail: null,

				editId: "",
				isDefault: false,
				formdata: {
					name: "",
					mobile: "",
					default: 0,
					country: "",
					province: "",
					city: "",
					citycode: "",
					district: "",
					adcode: "",
					formatted_address: "",
					address: ""
				},
				cities: []

			};
		},
		onLoad(data) {
			if (data.type == 1) {
				this.navTitle = '新增地址'
			} else {
				this.navTitle = '编辑地址'
				// this.editId = data.id
				console.log("data", data)
				if (data.address) {
					const value = decodeURIComponent(data.address)
					const _value = JSON.parse(value)
					console.log("value", _value)
					Object.keys(this.formdata).forEach(key => {
						if (_value[key]) {
							this.formdata[key] = _value[key]
						}
					})
					if (_value.default == 1) {
						this.isDefault = true
					}
					this.editId = _value.id
				}
			}
			// this.getCities()
		},
		methods: {
			result(res) {
				console.log(res)
				this.formdata.address = res.detail
				this.formdata.formatted_address = `${res.province}${res.city}${res.area}`
				this.formdata.province = res.province
				this.formdata.city = res.city
				this.formdata.district = res.area
				this.formdata.name = res.name
				this.formdata.mobile = res.phone
			},

			switchChange(e) {
				console.log("e", e)
				this.isDefault = e.detail.value
			},

			selectChange(text) {
				if (this.select_city_index == 0) {
					this.province = {
						text: text,
						value: 1
					}
					this.select_city_index = 1
					this.city = null
					this.arae = null
				} else if (this.select_city_index == 1) {
					this.city = {
						text: text,
						value: 2
					}
					this.select_city_index = 2
					this.arae = null
				} else if (this.select_city_index == 2) {
					this.arae = {
						text: text,
						value: 2
					}
					this.select_city_index = 3
					this.detail = null
				} else {
					this.detail = {
						text: text,
						value: 2
					}
				}
			},
			check(type) {
				this.select_city_index = type
			},
			closeSelectCity() {
				this.$refs.selectCity.close()

			},

			openLocation() {
				const that = this
				uni.getLocation({
					type: 'gcj02', //返回可以用于uni.openLocation的经纬度
					success: (res) => {
						const latitude = res.latitude;
						const longitude = res.longitude;
						uni.chooseLocation({
							latitude: latitude,
							longitude: longitude,
							success: (data) => {
								console.log('success', data);
								getLocation({
									lat: Number(data.latitude.toFixed(6)),
									lng: Number(data.longitude.toFixed(6))
								}).then(res => {
									console.log("res", res)
									const {
										adcode,
										city,
										citycode,
										country,
										district,
										province
									} = res.data.regeocode.addressComponent
									that.formdata.adcode = adcode
									that.formdata.city = city
									that.formdata.citycode = citycode
									that.formdata.country = country
									that.formdata.district = district
									that.formdata.province = province
									that.formdata.formatted_address = data.address
									that.formdata.address = data.name
									that.formdata.location = res.data.regeocode.addressComponent.streetNumber.location
								})
							}
						});
					}
				});

			},

			async save() {
				if(!this.formdata.name){
					uni.showToast({
						title: '请输入姓名',
						icon: 'none'
					})
					return
				}
				if(!this.formdata.mobile){
					uni.showToast({
						title: '请输入手机号',
						icon: 'none'
					})
					return
				}
				uni.showLoading({
					mask: true
				})
				try{
					const data = {
						...this.formdata,
						is_default: this.isDefault ? 1 : 0
					}
					if (this.editId) {
						data['id'] = this.editId
						console.log("编辑", data)
					} else {
						console.log("新增", data)
					}
					
					const res = await addUserAddress({
						type: this.editId ? 'edit' : 'add',
						data,
					})
					console.log("保存成功!", res)
					uni.showToast({
						title: "保存成功!"
					})
					uni.$emit("refreshAddressList")
					setTimeout(() => {
						uni.navigateBack()
					}, 500)
				}catch(e){
					//TODO handle the exception
					console.log("保存地址错误", e)
				} finally {
					uni.hideLoading()
				}
			},

			async getCities() {
				try {
					const res = await getCities()
					console.log("getCities res", res)
					this.cities = res.data.cities
				} catch (e) {
					//TODO handle the exception
					console.log("getCities e", e)
				}
			}
		}
	}
</script>

<style lang="scss" scoped>
	.container {
		.content {
			padding: 22rpx 22rpx 0;
			box-sizing: border-box;

			.form-box {
				background: #FFFFFF;
				box-shadow: 0rpx 0rpx 12rpx 2rpx rgba(223, 223, 223, 0.16);
				border-radius: 20rpx;

				/deep/ .pla-class {
					font-weight: 400;
					font-size: 28rpx;
					color: #B4B4B4;
					line-height: 40rpx;
				}

				&>view {
					padding: 32rpx 20rpx 34rpx 22rpx;
					box-sizing: border-box;

					&:not(:last-child) {
						border-bottom: 2rpx solid #EEEEEE;
					}
				}

				.city {
					display: flex;
					align-items: center;
					justify-content: space-between;

					.left {
						display: flex;
						width: calc(100% - 130rpx);

						image {
							width: 37rpx;
							height: 37rpx;
						}

						text {
							display: block;
							width: calc(100% - 37rpx);
							padding-left: 14rpx;
							box-sizing: border-box;
						}
					}

					.dw {
						display: flex;
						align-items: center;
						justify-content: flex-end;

						image {
							width: 32rpx;
							height: 39rpx;
							margin-right: 24rpx;
						}

						text {
							font-weight: 400;
							font-size: 28rpx;
							color: #333333;
							line-height: 40rpx;
						}
					}
				}

				.address {
					.left {
						width: 100%;

						input {
							width: calc(100% - 37rpx);
							padding-left: 14rpx;
							box-sizing: border-box;
						}
					}
				}

				.name-sex {
					display: flex;

					&>view {
						flex: 1;

						input {
							width: calc(100% - 37rpx);
							padding-left: 14rpx;
							box-sizing: border-box;
						}
					}

					.right {
						display: flex;
						justify-content: flex-end;

						.check {
							display: flex;
							align-items: center;

							image {
								width: 40rpx;
								height: 40rpx;
								margin-right: 8rpx;
							}

							text {
								font-weight: 400;
								font-size: 28rpx;
								color: #000000;
								line-height: 40rpx;
							}

							&:first-child {
								margin-right: 60rpx;
							}
						}
					}
				}

				.znsb {
					border-bottom: 2rpx solid #EEEEEE;

					/deep/ .resBtn {
						width: 154rpx;
						height: 52rpx;
						background: #0291FF;
						border-radius: 26rpx;
						padding: 0;
						font-weight: 400;
						font-size: 28rpx;
						color: #FFFFFF;
						line-height: 52rpx;
						text-align: center;
						border: none;
						margin: 0;
					}
				}

				.moren {
					display: flex;
					justify-content: space-between;
					align-items: center;
					padding-left: 36rpx;

					text {
						font-weight: bold;
						font-size: 32rpx;
						color: #333333;
						line-height: 44rpx;
					}

					switch {
						transform: scale(0.8);
					}
				}
			}
		}
	}

	.b-btn {
		position: fixed;
		bottom: 0;
		left: 0;
		right: 0;
		width: 100%;
		padding-bottom: constant(safe-area-inset-bottom);
		padding-bottom: env(safe-area-inset-bottom);

		.b-box {
			padding: 20rpx 22rpx;
			box-sizing: border-box;

			button {
				width: 100%;
				height: 96rpx;
				background: linear-gradient(135deg, #FFA233 0%, #FB4C4C 100%);
				border-radius: 80rpx;
				font-weight: bold;
				font-size: 36rpx;
				color: #FFFFFF;
				line-height: 96rpx;
			}
		}

		.edit {
			display: flex;
			justify-content: center;

			button {
				width: 50%;

				&:nth-child(1) {
					background: #FF4A4A;
					border-radius: 80rpx 0rpx 0rpx 80rpx;
				}

				&:last-child {
					background: linear-gradient(135deg, #FFA233 0%, #FB4C4C 100%);
					border-radius: 0rpx 80rpx 80rpx 0rpx;
				}
			}
		}
	}

	.select-city-box {
		.title {
			display: flex;
			align-items: center;
			justify-content: center;
			position: relative;
			padding-top: 28rpx;

			text {
				font-weight: bold;
				font-size: 36rpx;
				color: #333333;
				line-height: 50rpx;
			}

			image {
				position: absolute;
				top: 32rpx;
				right: 22rpx;
				width: 41rpx;
				height: 41rpx;
			}
		}

		.s-value {
			padding: 66rpx 22rpx 32rpx;
			box-sizing: border-box;
			display: flex;
			flex-direction: column;

			&>view {
				font-weight: bold;
				font-size: 28rpx;
				color: #000000;
				line-height: 40rpx;
				box-sizing: border-box;

				&:not(:first-child) {
					// margin-left: 120rpx;
					margin-top: 40rpx;

					.value {

						&.select,
						&.prev-select {
							&::after {
								content: '';
								width: 2rpx;
								height: 80rpx;
								background-color: #707070;

								position: absolute;
								left: 16rpx;
								bottom: 18rpx;
								z-index: 2;
							}
						}
					}
				}

				position: relative;

				.edit {
					font-weight: 400;
					font-size: 28rpx;
					color: #B4B4B4;
					line-height: 40rpx;
					margin-left: 20rpx;
				}

				.value {
					padding-left: 56rpx;

					&.select {
						&::before {
							content: '';
							display: inline-block;
							width: 32rpx;
							height: 32rpx;
							background: #E72A2A;
							border-radius: 50%;
							position: absolute;
							left: 0;
							top: 50%;
							transform: translateY(-50%);
							z-index: 3;
						}
					}

					&.prev-select {
						font-weight: 400;
						font-size: 28rpx;
						color: #B4B4B4;
						line-height: 40rpx;

						&::before {
							content: '';
							display: inline-block;
							width: 30rpx;
							height: 30rpx;
							background: #F8F8F8;
							border-radius: 50%;
							border: 2rpx solid #707070;
							position: absolute;
							left: 0;
							top: 50%;
							transform: translateY(-50%);
							z-index: 3;
						}
					}
				}
			}
		}

		.select-index {
			padding: 8rpx 22rpx 32rpx;
			box-sizing: border-box;

			text {
				font-weight: bold;
				font-size: 28rpx;
				color: #000000;
				line-height: 40rpx;
			}
		}

		.s-list {
			width: 100%;
			height: 582rpx;
			overflow-y: auto;
			padding: 0 22rpx 50rpx;
			box-sizing: border-box;

			.s-item {
				width: 100%;
				padding-left: 30rpx;
				box-sizing: border-box;
				position: relative;

				&>text {
					position: absolute;
					font-weight: 500;
					font-size: 28rpx;
					color: #000000;
					line-height: 40rpx;
					left: 0;
					top: 0;
				}

				.name {
					font-weight: 500;
					font-size: 28rpx;
					color: #000000;
					line-height: 40rpx;
					margin-bottom: 48rpx;
				}
			}
		}
	}
</style>